<?php
class model_custormvisit extends framework_base_model {
	//批量导入字段
	private static $_batch_keywords = array(
			'visit_custorm','custorm_unit','custorm_addr','custorm_maintain','recive_name','recive_study','recive_tel','recive_email','user_recent','cooperation','visible','openids','visiter_name','visiter_date','business_unit','cooperation_status','status','handle_msg','handle_date','author','editer'
		);
	private static $_betch_max = 299;
	/**
	 * @desc 添加走访信息
	 * @param array 
	 * @return number
	 */
	public static function custormvisitAdd($data) {
    	if(!is_array($data)) {
    		return 0;
    	}
    	try{
    		$sql = "insert into `weixin_customer_visited` set ";
    		$binds = array();
    		foreach ($data as $k => $v) {
    			$sql .= '`' . $k . '`=:' . $k . ',';
    			$binds[':' . $k] = $v;
    		}
    		$sql .= 'raw_add_time=NOW()';
    		$arr=self::DB() -> dbh -> prepare($sql);
    		$rel = $arr->execute($binds);
    		if($rel == TRUE) {
    			return self::DB()->dbh->lastInsertId();
    		} else {
    			return 0;
    		}
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return 0;
    	}
    }
	//获取归属单位
	public static function get_unit_category(){
		$sql = "select `unit_category_id`,`parent_id`,`category_name`,`depth` from `weixin_unit_category` where `delete_flag` = 0";
		$info = array();
		try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute();
    		$info = $st -> fetchAll();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $info;
	}
	//获取归属单位ID
	public static function get_unit_category_id($category_name){
		$sql = "select `unit_category_id` from `weixin_unit_category` where `category_name` = :category_name and `delete_flag` = 0";
		$id = 1;
		try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(':category_name' => $category_name));
    		$id = $st -> fetchColumn();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
		return $id;
	}
    /*
     * 根据ID获取新闻内容
     */
    public static function getCustormvisitById($id) {
    	$info = array();
    	if(intval($id) <= 0) {
    		return $info;
    	}
    	$sql = "select * from `weixin_customer_visited` where customer_visited_id=:customer_visited_id and delete_flag = 0";
    	try {
    		$st = self::DB() -> dbh -> prepare($sql);
    		$st -> execute(array(":customer_visited_id" => intval($id)));
    		$info = $st -> fetch();
    	} catch (Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    	}
    	return $info;
    }
    /**
     * @desc 更新订单内容
     * @param unknown $id
     * @param unknown $data
     * @return unknown|number
     */
    public static function updateCustormvisit($id,$data) {
    	try{
    		$sql = 'UPDATE `weixin_customer_visited` SET ';
    		$binds = array();
    		foreach ($data as $k => $v) {
    			$sql .= '`' . $k . '`=:' . $k . ',';
    			$binds[':' . $k] = $v;
    		}
    		$ids = implode(',',$id);
    		$sql = trim($sql,',');
    		$sql .= ' WHERE `customer_visited_id` in ('.$ids.')';
    		$stm=self::DB() -> dbh -> prepare($sql);
    		$rel = $stm->execute($binds);
    		$rowCount = $stm -> rowCount();
    		return $rowCount;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return false;
    	}
    }
    /**
     * 获取订单列表
     * @param number $nextNum
     * @param number $pagesize
     * @param unknown $condition
     * @return unknown|Ambigous <number, unknown>
     */
    public static function custormvisitList($nextNum = 0,$pagesize = 0,$condition = array()) {
    	$sql = "select `customer_visited_id`,`visit_custorm`,`custorm_unit`,`custorm_addr`,`custorm_maintain`,`recive_name`,`recive_study`,`recive_tel`,`recive_email`,`user_recent`,`cooperation`,`openids`,`visiter_name`,`visiter_date`,`cooperation_status`,`status`,`handle_msg`,`handle_date`,`business_unit` from `weixin_customer_visited` where `delete_flag` = 0";
		$where = "";
    	if(is_array($condition)&& count($condition)>0){
    		if(isset($condition['visit_custorm'])) {
    			$where .= " and visit_custorm like '%{$condition['visit_custorm']}%'";
    		}
			if(isset($condition['visiter_name'])) {
    			$where .= " and visiter_name like '%{$condition['visiter_name']}%'";
    		}
    	}
    	$where .= " order by `raw_add_time` desc";
    	$limit = "";
        if($pagesize != 0 ){
    		$limit = " limit {$nextNum},{$pagesize}";
    	}
    	$result = array();
    	try {
    		$st = self::DB()->dbh->prepare($sql.$where.$limit);
    		$st->execute();
    		$result = $st->fetchAll();
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		$result = array();
    	}
		
		$sql = "select count(*) from `weixin_customer_visited` where `delete_flag` = 0 {$where}";
		$binds2 = array();
    	try {
    		$st = self::DB()->dbh->prepare($sql);
    		$st->execute($binds2);
    		$count = $st->fetchColumn();
    		$result['count'] = $count;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		$result['count'] = 0;
    	}		
		return $result;
    }
	/*
	* @desc 批量写入订单
	* @author kevin wang
	* @param array
	* @return boolean
	*
	*/
	public static function batch_insert_cvisit(array $orders){
		if(empty($orders)){
			return false;
		}
		
		try{
			$sql = "";
			$bind = array();
			$i = 0;
			foreach($orders as $order){
				$sql .= "insert into `weixin_customer_visited` set ";
				foreach($order as $k=>$v){
					$key = self::$_batch_keywords[$k];
					if($key == 'visit_custorm' && empty($v)){
						continue;
					}
					if($key == 'cooperation_status'){
						$v = ($v == '合作中')?1:($v == '合作中断'?2:0);
					}
					if($key == 'business_unit' || $key == 'custorm_unit'){
						$v = self::get_unit_category_id($v);
					}
					if($key == 'status'){
						$v = ($v == '待审核')?0:($v == '已审核'?1:0);
					}
					if($key == 'visible'){
						$v = self::getAuthByName($v);
					}
					$sql .= "`{$key}` = ?,";
					$bind[] = empty($v)?"":$v;
				}
				$sql .= '`raw_add_time` = NOW();';
				$i++;
				if($i > self::$_betch_max){
					$sqls[] = $sql;
					$binds[] = $bind;
					$bind = array();
					$sql = "";
					$i = 0;
				}
				
			}
			//处理最后一个
			if(!empty($sql)){
				$sqls[] = $sql;
				$binds[] = $bind;
			}

			$pdo = self::DB() -> dbh;

			foreach($sqls as $key => $sqlv){
				$stm = $pdo -> prepare($sqlv);
    			$stm -> execute($binds[$key]);
			}
			
			return true;
    	}catch(Exception $e){
    		framework_static_function::write_log($e->getMessage(),'error_sql');
    		return false;
    	}
	}
	private static function getAuthByName($name){
		if($name == '内部用户'){
			return '1_8,1_9,1_10,1_11,1_12,1_13';
		}
		if($name == '外部用户'){
			return '2_3,2_4,2_5,2_6,2_7';
		}
		return '*_*';
	}
}
